# 将ply 文件转换为 color coord segment.npy 


import open3d as o3d
import numpy as np

def ply_to_npy(ply_path, output_prefix):
    # 读取PLY文件
    pcd = o3d.io.read_point_cloud(ply_path)
    
    # 提取坐标 (N,3)
    coords = np.asarray(pcd.points)
    
    # 提取颜色 (N,3) 并转换为0-255范围
    colors = (np.asarray(pcd.colors) * 255).astype(np.uint8)
    
    # 提取标签 (N,)
     # 手动解析文件获取scalar_label
    labels = []
    with open(ply_path, 'r') as f:
        # 跳过头部
        while True:
            line = f.readline()
            if "end_header" in line:
                break
                
        # 读取数据部分
        for _ in range(len(coords)):
            parts = f.readline().strip().split()
            labels.append(float(parts[6]))  # scalar_label是第7列（0-based索引6）
    
    labels = np.array(labels)
    print(labels)
    
    # 保存为.npy文件
    np.save(f"{output_prefix}_coord.npy", coords)
    np.save(f"{output_prefix}_color.npy", colors)
    np.save(f"{output_prefix}_segment.npy", labels)
    print(f"Saved to {output_prefix}_[coord/color/segment].npy")

# 使用示例

ply_path = 'E:\\data\\3DpointCloud\\松霖人脸数据\\face_seg\\960_1322612098152402944-17353769613083DresultWHITE\\WHITE - Cloud.ply'
# ply_path = "E:\\data\\3DpointCloud\\松霖人脸数据\\face_seg_clean\\960_1323236387721449472-17355257921513Dresult\\Merged mesh.ply"
ply_to_npy(ply_path, "output")